Skip to content

devtip/JavaScript-Tips

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 

Repository files navigation

JavaScript-Tips

偶然看到JavaScript Tips。这个项目是每天分享一个JavaScript Tip,受到这个项目的启发,我也打算每天更新一个小Tip,我会参考原文,如果觉得写的很不错,我也会仅仅充当翻译工,但是每一个Tip都会加入我自己的思考,思考如果是我来写这个Tip的话,我会怎么写。

经验不足,能力有限,还望轻拍。

####2016-01-09: 为数组或者单个元素应用相同的函数

举例:

var a = "sun";
var b = ["sun","hui"];

现在需要将a转换成大写,将b中的每个元素都转换成大写,通常的做法是:

console.log(a.toUpperCase());     			// "SUN"
for(var i=0;i<b.length;i++){
	console.log(b[i].toUpperCase());      // "SUN" "HUI"
}

这种做法相当于写了两套代码,看看下面的方式。

function toUpper(words){
	var elements = [].concat(words);
	for(var i=0;i<elements.length;i++){
		console.log(elements[i].toUpperCase());
	}
}

toUpper("sun");								// "SUN"
toUpper(["sun","hui"]);						// "SUN" "HUI"

关键点是:concat的用法,str.concat(arg)的参数arg如果是一个数组会把数组里的(不是嵌套数组的)每一项都拿出来作为新数组的元素。

####2016-01-08:null和undefined的区别

  • undefined表示变量没有被声明或者声明了但是没有被赋值。
  • null表示这个变量不是一个值。
  • JavaScript里没有被赋值的变量默认为undefined
  • JavaScript里不会把一个值设置为null,只有程序员自己才能把一个值设置为null
  • 在JSON里undefined不可用,而null是可用的。
  • type of undefined的值为undefined
  • type of null的值为object
  • nullundefined的布尔值都为false。
  • null == undefined的值为true
  • null === undefined的值为false

####2016-01-07:往数组中插入一个元素

一般而言,对数组元素的操作我们会用到这些函数:pushpopunshiftshiftsplice

	var a = [1, 2, 3];
	a.push(4);
	console.log(a);     //[1,2,3,4]
	a.pop();					
	console.log(a);		//[1,2,3]
	a.unshift(5);
	console.log(a);		//[5,1,2,3]
	a.shift();
	console.log(a);		//[1,2,3]
	a.splice(0,2,6);
	console.log(a)		//[6,3]

我在这里想介绍的是利用length属性来进行数组元素的增减。

	var a = [1, 2, 3];
	a.length = 1;
	console.log(a);		//[1]
	a.length = 5;
	console.log(a);		//[1,undefined,undefined, undefined, undefined]
	a = [1,2,3];
	a.splice(a.length/2,0,4,5,6);		//在数组的中间插入元素
	console.log(a);		//[1,4,5,6,2,3]

值得注意的是以上所有方法都改变了原数组。我们再来一个:

	var a = [1,2,3];
	var b = [4,5].concat(a);
	console.log(a);		//[1,2,3]
	console.log(b);		//[4,5,1,2,3]

使用concat来增加数组元素就会返回一个新数组,不会改变原数组,

About

a JavaScript tip every day

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors