JavaScriptの配列はlengthを使えば先頭からいくつか切り取れる

問題: 次の中でresultが異なるのはどれか

var array = ['one', 'two', 'three']
var result = array.splice(0, 2)
console.log(result)

var array = ['one', 'two', 'three']
var result = array.slice(0, 2)
console.log(result)

var array = ['one', 'two', 'three']
array.pop()
var result = array
console.log(result)

var array = ['one', 'two', 'three']
array.length = 2
var result = array
console.log(result)

シンキングタイムは30秒

正解はこちらをクリック
答えはすべて同じで ["one", "two"] になる。
slice以外は破壊的でarrayの内容が変わる点に注意。
JavaScriptを仕事で書く人でもこれらを理解していない人が多い。

var array = ['one', 'two', 'three']
var result = array.splice(0, 2)
console.log(result)
// => ["one", "two"]
console.log(array)
// => ["three"]

var array = ['one', 'two', 'three']
var result = array.slice(0, 2)
console.log(result)
// => ["one", "two"]
console.log(array)
// => ["one", "two", "three"]

var array = ['one', 'two', 'three']
array.pop()
var result = array
console.log(result)
// => ["one", "two"]
console.log(array)
// => ["one", "two"]

var array = ['one', 'two', 'three']
array.length = 2
var result = array
console.log(result)
// => ["one", "two"]
console.log(array)
// => ["one", "two"]