JS Array play around

original_galaxy發表於2018-09-01

delete

// 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
複製程式碼

slice VS splice

arr.slice([begin[, end]])

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.

  • begin(optional): Zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of the sequence.
  • end(optional): Zero-based index before which to end extraction. Also a negative index can be used, indicating an offset from the end of the sequence.
  • return value: A new array containing the extracted elements.
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"]
複製程式碼

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

  • start: index at which start to change the array(with origin 0)
  • deleteCount(optional): An integer indicating the number of old array elements to remove.
  • item(optional): The elements to add to the array, beginning at the start index.
  • return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
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
複製程式碼

ways to verify if a variable is Array

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
複製程式碼

de-duplicated elements in Array

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)];
複製程式碼

reference

Array.prototype.slice()

Array.prototype.splice()

JavaScript專題之陣列去重

相關文章