在Javascript中查找数组中的值

时间:2013-04-23 22:57:12

标签: javascript arrays node.js replace find

我试图找出数组中是否存在值。以下代码每次运行时都会给我一个错误,说对象没有替换方法。

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(); }

});

一开始,无论我输入什么,它都会不断返回“没有找到价值”,所以我推测这是我进入水果后按下的换行/进入。但水果的替代方法拒绝采取。我错过了什么?

1 个答案:

答案 0 :(得分:0)

如果您尚未使用setEncoding方法,则data事件会获得Buffer个对象,而不是字符串。

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

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

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