数组推送函数在数组中再添加一个空索引

array push function adds one more empty index into array

本文关键字:数组 一个 索引 添加 函数      更新时间:2023-09-26
function spacing(num){
    var a=[];
    var aToStr="";
    for(i=0;i<num;i++) {
        a.push("&nbsp")
    }
    for(i=0;i<a.length;i++) {
        aToStr=a[i]+aToStr;
    }
    // alert(a.length);result is 5 here
    // alert(aToStr.split("&").length);//here result is 6 and when printed to screen theres an empty index
    return aToStr;
} 

正如我在代码中解释的那样。数组中发生了一些事情,不知何故又出现了 1 个索引。当我将其打印到屏幕时,该索引中只有一个空格。

首先,您的问题应简化为:

为什么

"&nbsp&nbsp".split("&").length

是 3 而不是 2 ?

为什么

"&".split("&").length

是 2 而不是 0 ?

对于最后一个版本,答案是 JavaScript 认为你有 2 个空字符串s (""):其中一个在分隔符之前,另一个在分隔符之后。为什么?这就是他们决定实现此功能的方式=>只是一个决定。在 Java 中,类似的尝试将返回 0

如果您认为这很奇怪,请注意"a".split("b").length返回1

所以,JavaScript认为answer = 1 + numberOfAppearancesForThatSeparator

来自 MDN:

找到后,将从字符串中删除分隔符,并在数组中返回子字符串。

错误解释:

  1. split开始搜索,首先找到和

    &nbsp&nbsp&nbsp&nbsp&nbsp
    // & found and removed, resulting in  ' '
    // returnArrForSplit = ['']
    
  2. 找到第二个和

    nbsp&nbsp&nbsp&nbsp&nbsp
    // & found and removed, everything before pushed to returnArrForSplit, 'nbsp'
    // returnArrForSplit = ['', nbsp]
    
  3. 第三和

    nbsp&nbsp&nbsp&nbsp
    // & found and removed, resulting in  'nbsp'
    // returnArrForSplit = ['', nbsp, nbsp]
    
  4. 第四和

    nbsp&nbsp&nbsp
    // & found and removed, resulting in  'nbsp'
    // returnArrForSplit = ['', nbsp, nbsp, nbsp]
    
  5. 决赛和

    nbsp&nbsp
    // & found and removed, resulting in  'nbsp'
    // returnArrForSplit = ['', nbsp, nbsp, nbsp, nbsp]
    
  6. 但还剩下一个nbsp

    nbsp
    // added as last substring
    // returnArrForSplit = ['', nbsp, nbsp, nbsp, nbsp, nbsp]
    returnArrForSplit.shift()
    // removes unwanted empty string.
    

固定代码

function spacing(num){
    var a=[];
    var aToStr="";
    for(i=0;i<num;i++) {
        a.push("&nbsp")
    }
    for(i=0;i<a.length;i++) {
        aToStr=a[i]+aToStr;
    }
    return aToStr;
}
var spaces = spacing(5);
// "&nbsp&nbsp&nbsp&nbsp&nbsp"
spaces = spaces.split('&');
// ["", "nbsp", "nbsp", "nbsp", "nbsp", "nbsp"]
spaces.shift() // returns ''
// spaces is ["nbsp", "nbsp", "nbsp", "nbsp", "nbsp"]