// diff between array and object
var number = [0, 1, 2]
delete number[2]
console.log(number) // [0, 1, empty]
console.log(number.length) // 3
console.log(number[2]) // undefined
var json = {x: 'x', y: 'y'}
delete json['x']
console.log(json) // {y: "y"}
console.log(json['x']) // undefined
複製代碼
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included). The original array will not be modified.git
let emoji = ['smile', 'wry smile', 'snigger']
emoji.slice(1) // ['wry smile', 'snigger']
emoji.slice(0, 2) // ['smile', 'wry smile']
// slice from the second end of the sequence to the first end(first end not included)
emoji.slice(-2, -1) // ["wry smile"]
複製代碼
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.github
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb'); // inserts at 1st index position
console.log(months); // Array ['Jan', 'Feb', 'March', 'April', 'June']
months.splice(4, 1, 'May'); // replaces 1 element at 4th index
console.log(months); // Array ['Jan', 'Feb', 'March', 'April', 'May']
// so actually the basic explanation for this method is:
// => from the start, remove zero/more, then add zero/more
複製代碼
let arr = ['apple', 'huawei'];
Array.isArray(arr); // true
arr.constructor === Array; // true
console.log(arr instanceof Array); // true
Object.prototype.toString.call(arr) === '[object Array]'; // true
複製代碼
let cities = ['Shanghai', 'Beijing', 'NYC', 'LA', 'Tokyo', 'Auckland', 'LA']
let newCities = []
// 1. basic cycle plus indexOf(), notice that indexOf() is supported by at least IE9
for(let i=0; i<cities.length; i++) {
if(newCities.indexOf(cities[i]) === -1) { // indicates no existing
newCities.push(cities[i])
}
}
// 2. based on indexOf() returns index of the first ele which is included
newCities = cities.filter(function(ele, index, array) {
return array.indexOf(ele) === index;
})
// 3. a better one which is compatible under IE9
for(var i = 0; i < cities.length; i++) {
for(var j = 0, refLen = newCities.length; j < refLen; j++ ) {
if(cities[i] === newCities[j]) {
break;
}
}
// j === refLen shows that cities[i] was not found in newCities at all, so push
if(j === refLen) {
newCities.push(cities[i])
}
}
// 4. note: from() is not supported by IE, but this is really concise
newCities = Array.from(new Set(cities))
// 5. at last, the one
newCities = [...new Set(cities)];
複製代碼