【问题标题】:Finding values in an Array in Javascript在Javascript中查找数组中的值
【发布时间】:2013-04-17 07:52:06
【问题描述】:

我试图找出一个值是否存在于数组中。每次我运行说 Object has no replace 方法时,以下代码都会给我一个错误。

var fruits = ['apples', 'pears', 'bananas'];

console.log("Enter in a fruit name");

process.stdin.on('data', function(fruit) {

    fruit = fruit.replace("\n", "");
    if (fruits.indexOf(fruit) >= 0 ) {
        console.log("The value has been found in the array");
        process.exit(); }

    else {
        console.log("Value not found");
        process.exit(); }

});

起初,无论我输入什么,它都会一直返回“找不到值”,所以我推测这是我输入水果后按的换行符/输入。但水果的替换方法拒绝采取。我错过了什么?

【问题讨论】:

  • 试试console.log(JSON.stringify(fruit))看看你在搜索什么。

标签: javascript arrays node.js replace find


【解决方案1】:

如果您没有使用过setEncoding 方法,data 事件将获得一个Buffer 对象,而不是字符串。

使用toString方法将缓冲区中的数据解码为字符串:

var fruitName = fruit.toString().replace("\n", "");

您在数组中没有找到任何内容的原因可能是您正在寻找Buffer 对象而不是字符串。在这种情况下,您可能根本不需要replace

【讨论】:

猜你喜欢
  • 2015-08-27
  • 2017-12-02
  • 2011-09-26
  • 2021-11-14
  • 2011-07-08
  • 2018-08-30
  • 1970-01-01
相关资源
最近更新 更多