2013-04-23 80 views
0

我试图找出数组中是否存在值。下面的代码每次运行时都会给我一个错误,表示Object没有替换方法。在Javascript中查找数组中的值

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

}); 

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

+0

什么是'水果'? – 0x499602D2 2013-04-23 23:03:37

+0

尝试'console.log(JSON.stringify(水果))'看看你在寻找什么。 – Bergi 2013-04-23 23:04:49

回答

0

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

使用toString方法对数据进行解码的缓冲区的字符串:

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

这有可能是你没有找到在阵列中的任何原因是你要找的Buffer对象而不是一个字符串。在这种情况下,你可能不需要replace

+0

谢谢!如果其他人对此感兴趣的话,可以用Guffa的帮助拼凑起来: https://gist.github.com/jennojenno/5448370 – jenno 2013-04-23 23:38:27