Javascript 打印没有逗号分隔符的数组(对象?)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14997984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:35:58  来源:igfitidea点击:

Print an array(object?) without comma seperator

javascriptarraysobjectoutputcomma

提问by Dohrann

I am currently writing a large amount of code, but I will keep it simple. I have a javascript array (possibly an object, still unsure exactly of the conventional naming), here is the initialization code:

我目前正在编写大量代码,但我会保持简单。我有一个 javascript 数组(可能是一个对象,仍然不确定传统的命名方式),这里是初始化代码:

var myArray = ["assignS" , ";" , "S"]

This is what I get as a console.log() from firebug on the element. There is too much code to post as it is assigned multiple values through many for loops. So this array (or object) is printed later as follows:

这是我从元素上的萤火虫获得的 console.log() 。有太多代码需要发布,因为它通过许多 for 循环分配了多个值。所以这个数组(或对象)稍后打印如下:

document.write("S -> " + myArray);

output:

输出:

 S -> assignS,;,S

I do not want these commas in the result, it poses problems as some elements in the array may be commas themselves. I have ruled out the .join() method because of this, and am unsure how to proceed.

我不希望这些逗号出现在结果中,它会带来问题,因为数组中的某些元素本身可能是逗号。因此,我已经排除了 .join() 方法,并且不确定如何继续。

回答by Daedalus

You ruled out the join method why, exactly? It takes a parameter, the separator, which you can then use to specify noseparator:

你排除了 join 方法,为什么?它需要一个参数分隔符,然后您可以使用它来指定没有分隔符:

myArray.join("");

I recommend reading up on the documentation for .join(). Also, I wouldn't recommend you use document.write, it has very few good applications.

我建议在阅读了有关文档.join()。另外,我不建议您使用document.write,它很少有好的应用程序。

回答by steveukx

The .joinmethod on an array will by default concatenate all items with a comma, but it takes one argument to override this to be any other string to use as the glue - including an empty string.

所述.join阵列上的方法将被默认连接具有逗号的所有项目,但它需要一个参数来覆盖这是任何其他字符串作为胶使用-包括空字符串。

myArray.join(''); // is "assignS;S"

回答by murtuza

var a=[1,2,3,4]
var result="";
for(i= a.length-1; i>=0;i--){
    result=a[i]+result;
}

document.getElementById("demo").innerHTML=result;

回答by murtuza

Use this code:

使用此代码:

document.write("S -> " + myArray.join(" "));