![](/img/trans.png)
[英]Javascript to finding muptiple values in a string and saving to an array?
[英]Finding values in an Array in 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(); }
});
最初,无论我输入什么内容,它都会一直返回“找不到值”,因此我推测这是我输入水果后按下的换行/输入。 但是水果的替换方法拒绝采取。 我想念什么?
如果尚未使用setEncoding
方法,则data
事件将获取Buffer
对象,而不是字符串。
使用toString
方法将缓冲区中的数据解码为字符串:
var fruitName = fruit.toString().replace("\n", "");
在数组中找不到任何内容的原因可能是您在寻找Buffer
对象而不是字符串。 在这种情况下,您可能根本不需要replace
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.