简体   繁体   English

JavaScript 数组在索引处拆分

[英]JavaScript array split at index

I have an array like:我有一个数组,如:

var arr = ['Number 1', 'name', 'Number 2', 'name']

How can I get a string from this array that looks like this:如何从此数组中获取如下所示的字符串:

var str = 'Number 1: name, Number 2: name'

For this, you'd probably want Array#reduce , see the comments:为此,您可能需要Array#reduce ,请参阅评论:

 // The array var arr = ['Number 1', 'name', 'Number 2', 'name'] // Start with no delimiter var delim = ""; // Array#reduce calls the callback once for each entry, passing in // the accumulator as the first argument and the entry as the second var str = arr.reduce(function(acc, entry) { // Add this entry onto the accumulator acc += delim + entry; // Toggle between ", " and ": " as the delim (the first time we have // "", which means we'll switch to ": ") delim = delim === ", " ? ": " : ", "; // Return the new value of the delim return acc; }, ""); // ^^---- initial value of the accumulator is blank document.body.innerHTML = "<pre>" + str + "</pre>";

Alternately, you can do it with the other variant of reduce where you don't give an initial value for the accumulator:或者,您可以使用不为累加器提供初始值的reduce的其他变体来执行此操作:

 // The array var arr = ['Number 1', 'name', 'Number 2', 'name'] // Start with the first delimiter we want to use var delim = ": "; // Array#reduce calls the callback slightly differently the // first time: It passes entry 0 as the first argument and entry 1 // as the second. From then on it keeps passing the accumulator. var str = arr.reduce(function(acc, entry) { // Add this entry onto the accumulator acc += delim + entry; // Toggle between ", " and ": " as the delim (the first time we have // "", which means we'll switch to ": ") delim = delim === ": " ? ", " : ": "; // Return the new value of the delim return acc; }); document.body.innerHTML = "<pre>" + str + "</pre>";

Or actually, you could use map and join :或者实际上,您可以使用mapjoin

 // The array var arr = ['Number 1', 'name', 'Number 2', 'name'] // Append the desired delimiter to each entry except the last, // then join the resulting array var str = arr.map(function(entry, index) { if (index < arr.length - 1) { entry += index % 2 == 1 ? ", " : ": "; } return entry; }).join(""); document.body.innerHTML = "<pre>" + str + "</pre>";

You can do it by,你可以这样做,

var arr = ['Number 1', 'name', 'Number 2', 'name'],res ="";
for(var i=0,len=arr.length;i<len;i+=2){
  res += arr[i] + ":" + arr[i+1] + ((i+2 != len) ? "," : "");
}

set your for loop's step as 2. During iteration get the array's values related to current index and current index + 1 .将 for 循环的步骤设置为 2。在迭代期间,获取与current indexcurrent index + 1相关的数组值。 Concatenate it by giving a delimiter as : .通过将分隔符作为:连接它。 And your job is done.你的工作已经完成。

DEMO演示

You can use .join() with .replace() :您可以将.join().replace()

 var arr = ['Number 1', 'name', 'Number 2', 'name']; var s = arr.join(',').replace(/(\\d)+/g, '$1:').replace(/(:,)/g, ':'); document.write('<pre>'+s+'</pre>')

This code will give you correct output as needed ->此代码将根据需要为您提供正确的输出 ->

    var str = "";
    var arr = ['Number 1', 'name', 'Number 2', 'name'];
    var i=0;
    while(i<arr.length)
   {

   str += i==0 ? "" : ","
    str+=arr[i];
    i++;
    str+=":";
    str+=arr[i];

   }

You shouldn't use string concatenation when there is another solution, simply because it's less readable and harder to maintain.当有另一种解决方案时,您不应该使用字符串连接,因为它的可读性较差且难以维护。

 var arr = ['Number 1', 'name', 'Number 2', 'name']; var str = Array.from({length: arr.length / 2}).map(() => arr.splice(0, 2).join(' :')).join(', '); document.body.innerHTML = `<pre>${str}</pre>`;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM