![](/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.