简体   繁体   English

jQuery在数组的最后一个元素之前添加文本

[英]jQuery add text before final element of an array

I have an array: 我有一个数组:

var countryArray = [];

That I'm dynamically inserting values to with click events: 我正在通过点击事件动态地向其中插入值:

(on click...) (点击...)

countryArray.push("Australia");

and then finally appending to a div for output: 然后最后附加到div进行输出:

$('#summary-countries').append(countryArray+'');

So my output could be: 所以我的输出可能是:

Australia,United Kingdom,Finland,Japan.

Is there any way how I could insert some text so that it would output as the following: 有什么办法可以插入一些文本,使其输出如下:

Australia,United Kingdom,Finland **AND** Japan.

Any help would be appreciated! 任何帮助,将不胜感激!

Here's one way: 这是一种方法:

var countries;

if( countryArray.length > 1 ) { 
    var last = countryArray.pop();
    countries = countryArray.join(', ')+' and '+last;
}
else {
    countries = ''+countryArray;
}

$( '#summary-countries' ).append( countries );

Yes, there is a way. 是的,有办法。 You are relying on the built-in serialization of arrays, when you call .append(reasonsTravelling+''); 当您调用.append(reasonsTravelling+'');时,您依赖于数组的内置序列化.append(reasonsTravelling+''); . This converts reasonsTravelling into a string, which, by default is a comma separated list. 这会将reasonsTravelling转换为字符串,默认情况下,该字符串是逗号分隔的列表。

You have to use a for loop instead and go through all the items in the array. 您必须改用for循环,并遍历数组中的所有项目。 Once you find that the iterator is one before the last index , use the "And" instead of ",". 一旦发现迭代器one before the last index ,请使用“ And”代替“,”。

This fiddle should explain my idea: http://jsfiddle.net/v76Bf/ 这个小提琴应该解释我的想法: http : //jsfiddle.net/v76Bf/

You can traverse through and array and find the last index and insert the text before the last value. 您可以遍历和数组,找到最后一个索引,然后在最后一个值之前插入文本。

for (var i=0;i<countryArray.length;i++)
{
if(i==countryArray.length-1)
{
countryArray[i].join(,).push("And");
}
}

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

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