[英]Finding values in an Array in Javascript
I'm trying to find out if a value exists in an array. 我试图找出数组中是否存在值。 The following code is giving me an error each time I run saying Object has no replace method.
每次运行时,以下代码给我一个错误,即对象没有替换方法。
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(); }
});
At first it kept returning "Value not found" no matter what I entered, so I surmised it was the line break/enter that I press after entering my fruit. 最初,无论我输入什么内容,它都会一直返回“找不到值”,因此我推测这是我输入水果后按下的换行/输入。 But the replace method for the fruit refuses to take.
但是水果的替换方法拒绝采取。 What am I missing?
我想念什么?
If you haven't used the setEncoding
method, the data
event gets a Buffer
object, not a string. 如果尚未使用
setEncoding
方法,则data
事件将获取Buffer
对象,而不是字符串。
Use the toString
method to decode the data in the buffer to a string: 使用
toString
方法将缓冲区中的数据解码为字符串:
var fruitName = fruit.toString().replace("\n", "");
It's possible that the reason that you didn't find anything in the array is that you were looking for the Buffer
object instead of a string. 在数组中找不到任何内容的原因可能是您在寻找
Buffer
对象而不是字符串。 In that case you might not need the replace
after all. 在这种情况下,您可能根本不需要
replace
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.