首页 > 代码库 > good

good

1,将NodeList 转化成 Array
var divs = Array.from(document.querySelectorAll(‘div‘));
2,将 arguments 转化成 Array
function something() {
var args = Array.from(arguments);

// Array[‘yes‘, 1, {}]
}
something(‘yes‘, 1, {});
3,将 String 转化成 Array
Array.from(‘JavaScript‘); // 很像‘JavaScript‘.split(‘‘)

4,+ string to number
console.log(+new Date())

conected && login();
this.name = name || "Oliver Queen";

var length = array.length;
for(var i = 0; i < length; i++) {
console.log(array[i]);
}

var array = [1,2,3,4,5,6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]

数组截断
var array = [1,2,3,4,5,6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]

替换所有
var string = "john john";
console.log(string.replace(/hn/, "ana")); // "joana john"
console.log(string.replace(/hn/g, "ana")); // "joana joana"
合并数组
var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.concat(array2)); // [1,2,3,4,5,6];

var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // Now the NodeList is an array
var arrayElements = Array.from(elements); // This is another way of converting

var list = [1,2,3];
console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]

good