简体   繁体   English

在Java数组中查找值

[英]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.

相关问题 Javascript 在字符串中查找多个值并保存到数组? - Javascript to finding muptiple values in a string and saving to an array? Javascript-For循环无法在数组中正确找到值 - Javascript - For Loop not finding values in array correctly Javascript:跨多个数组查找共享值 - Javascript: Finding shared values across multiple array 查找类似的值并将项目附加到数组(javascript) - Finding like values and appending items to array (javascript) Javascript:查找数组中具有特定属性和值的所有对象 - Javascript: finding all objects in an array which have certain properties and values Javascript:在数组/对象中查找值以确定表单显示 - Javascript: Finding values in array/object to determine Form display 使用javascript查找同一对象数组中存在的两个值 - Finding two values existing in same object array using javascript 查找 JavaScript 数组值的所有组合(笛卡尔积),然后对它们进行排序 - Finding All Combinations (Cartesian product) of JavaScript array values and then ordering them Javascript - 从值数组中查找线段的长度 - Javascript - Finding length of line segments from an array of values 在Javascript中在一维数组中查找最小值和最大值之间的值 - Finding values between min and max in 1d array in Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM