javascript 在 js 中打印数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12677535/
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-10-26 16:50:32  来源:igfitidea点击:

printing array values in js

javascriptarraysstringcode-translation

提问by

I'm trying to create a function that will run through an array and collect it's value to a string that looks like this: '[1,2,3]'. I also need it to present only part of the array in some cases, according to a given index. For example: the array [1,2,0] printed from index 0 to index 1 will look like this: '[1,2]'. For some reason my function don't give any output at all. Here it is:

我正在尝试创建一个函数,该函数将运行一个数组并将其值收集到一个如下所示的字符串中:'[1,2,3]'。根据给定的索引,我还需要它在某些情况下仅显示数组的一部分。例如:从索引 0 打印到索引 1 的数组 [1,2,0] 将如下所示:'[1,2]'。出于某种原因,我的函数根本不提供任何输出。这里是:

function Tower(size, isFull) {
    this.count = 0;
    this.tower = new Array(size);

    this.add = function(disk) {
        this.tower[this.count++] = disk;
    };

    if (isFull) {
        for (var i = 1; i <= size; i++) {
            this.add(i);
        };
    }

    this.canAdd = function(disk) {
        return this.count == 0 || this.tower[this.count - 1] > disk;
    };

    this.getTopDiskValue = function() {
        return (this.count > 0) ? this.tower[this.count - 1] : 0;
    };

    this.popTop = function() {
        return this.tower[--this.count];
    };

    this.isFull = function() {
        return this.count == this.tower.length;
    };

    this.printable = function() {
        var output = "[";
        for (var i = 0; i < this.count; i++) {
            output += "" + this.tower[i] + ',';
        }
        return output.substring(0, output.length() - 1) + (output.length() > 1 ? ']' : "");
    };
}

I expect the printable() function to return the string so that the code:

我希望 printable() 函数返回字符串,以便代码:

var tower = new Tower(3,true);
alert(tower.printable());

will pop an alert box with the text '[1,2,3]' on it. This object is a translation from Java. It worked great in java btw, I guess the translation is not perfect.

将弹出一个带有文本“[1,2,3]”的警告框。这个对象是从 Java 翻译过来的。顺便说一句,它在 java 中效果很好,我想翻译并不完美。

采纳答案by Bergi

JavaScript is not Java - you don't get the length of an array or string by calling its .length()method, but just by retrieving its .lengthproperty. The exception which is thrown when you try to invoke the number is what crashes your script and prevents the alert. This would work:

JavaScript 不是 Java - 你不能通过调用它的.length()方法来获得数组或字符串的长度,而只是通过检索它的.length属性。当您尝试调用该号码时引发的异常会使您的脚本崩溃并阻止警报。这会起作用:

this.printable = function() {
    var output = "[";
    for (var i = 0; i < this.count; i++) {
        output += "" + this.tower[i] + ',';
    }
    return output.substring(0, output.length - 1) + (output.length > 1 ? ']' : "");
};

However, you just can use the native .join()methodto concatenate the array's values. Also, you should add your methods on the prototype of your Towerobjects:

但是,您只能使用本机.join()方法来连接数组的值。此外,您应该在Tower对象的原型上添加方法:

Tower.prototype.printable = function() {
    if (this.count)
        return "[" + this.tower.slice(0, this.count).join(",") + "]";
    else
        return "";
};

Btw: Usually this method is named toString- not only for convenience, but also it would get used when a Tower object is casted to a string value.

顺便说一句:通常这个方法被命名toString- 不仅是为了方便,而且在 Tower 对象被转换为字符串值时也会使用它。

回答by Denys Séguret

What you do is much too complicated.

你做的事情太复杂了。

Let's say you have an array declared as

假设你有一个数组声明为

var array = [1, 2, 3];

you get the desired string with

你得到了想要的字符串

return '['+array.join(',')+']';

You don't need pop or add functions, they're also native (and heavily optimized) :

您不需要 pop 或 add 函数,它们也是原生的(并且经过大量优化):

var last = array.pop()
array.push(newItem);

Reference :

参考 :

Note that all browsers offer a console, in which you'll find a detailed explanation of your errors. Have a look for example at the Chrome Developer Tools.

请注意,所有浏览器都提供了一个控制台,您可以在其中找到错误的详细说明。看看Chrome Developer Tools 的例子。

回答by hunter

use the Array.join()method:

使用Array.join()方法:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/join

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/join



this.printable = function() {
    var output = new Array();
    for (var i = 0; i < this.count; i++) {
        output.push(this.tower[i]);
    }
    return output.length == 0 
        ? "" 
        : "[" + output.join(",") + ']';
};

or if it's as simple as it looks:

或者如果它看起来很简单:

this.printable = function() {
    return this.count == 0 
        ? "" 
        : "[" + this.tower.join(",") + ']';
};