JavaScript中对空string挪用split返回不是空数组

今天在工作中发明一个诡异的题目,理论上应该是没有元素的数组,长度居然是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.

    原文作者:BetaRabbit
    原文地址: https://segmentfault.com/a/1190000004360749
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞