今天在工作中发明一个诡异的题目,理论上应该是没有元素的数组,长度居然是1。查了半天,原来是Javascript中的split和其他语言中差别,即对空string运用split会返回含有一个空string的数组,而不是一个空数组。
var str = "",
arr = str.split("_");
console.log(arr.length === 1); //true
console.log(arr === []); //false
console.log(arr === [""]); //true
参考MDN,也有相似的申明。
Note: When the string is empty, split returns an array containing one empty string, rather than an empty array.