替换,如果/否则

时间:2018-06-28 18:43:51

标签: javascript arrays algorithm

问题是:

  

创建一个接受数组的函数,并在您打印数组时   它表明“好吃”已替换了字符串的每个实例   “餐饮”。如果不存在数组元素或不存在数组   说“食物”的元素,然后一次打印“我饿了”。

给出的数组是:

  

[“你好”,2,“周杰伦”,“食物”,34、34,“食物”]

我想出的算法如下:

function alwaysHungry() {
  var arr = ["hello", 2,"Jay","food",34,34,"food"];
  for (var i = 0; i < arr.length; i++){
    if(arr[i] == "food"){
      arr[i]="yummy";
      console.log(arr);
    }
    else if (arr.length == 0 || arr[i] != "food"){
  
      console.log("I am hungry");
    
    }   
  }
    
}
alwaysHungry();

这是我的输出:

3VM578:12 I am hungry
VM578:8 (7) ["hello", 2, "Jay", "yummy", 34, 34, "food"]
2VM578:12 I am hungry
VM578:8 (7) ["hello", 2, "Jay", "yummy", 34, 34, "yummy"]

根据我拥有的数组,我应该只在输出中看到[“ hello”,2,“ Jay”,“ yummy”,34、34,“ yummy”],如果我将数组设为空,则应该看到“我饿了”,但不能同时饿死。

更新

下面的许多示例给我打印了两行,应该打印出数组或语句“我饿了”,但不能同时打印。

7 个答案:

答案 0 :(得分:2)

如果找到带有'food'的项目,则可以标记并设置该标记。最后,检查该标志并输出所需的结果。

您不需要对数组的length进行额外的检查,因为该标志会获得正确的起始值,并且for循环会在第一个条件下直接退出。

为了更方便地使用该函数,请对数组使用该函数的参数。

function alwaysHungry(array) {
    var i, hungry = true;
    for (i = 0; i < array.length; i++) {
        if (array[i] === "food") {
            array[i] = "yummy";
            hungry = false;
        }
    }
    if (hungry) {
        console.log("I am hungry");
    } else {
        console.log(array);
    }
}

alwaysHungry([]);
alwaysHungry(["hello", 2, "Jay", "food", 34, 34, "food"]);
alwaysHungry(["hello", 2, "Jay", "abc", 34, 34, "def"]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

我认为这就是您想要的(如果您正在寻找ES6语法):

var inputArray1 = ["hello", 2,"Jay","food",34,34,"food"]
var inputArray3 = ["hello", 2,"Jay","foo",34,34,"boo"]
var inputArray2 = []

function foodFinder(arr) {
  return (   (arr.length == 0) || 
         (!arr.includes("food"))  ) ? 
                                   "I am hungry" 
                                   : arr.map(e => (e + '').includes("food") ? "yummy" : e)
}

console.log(foodFinder(inputArray1))
console.log(foodFinder(inputArray2))
console.log(foodFinder(inputArray3))

答案 2 :(得分:1)

var alwaysHungry = function(array)
{
	if(!array.length || !array.includes("food"))
	{
		return console.log("I am hungry");
	}

	console.log(array.map(function(item)
	{
		return item == "food" ? "yummy" : item;
	}));
}

alwaysHungry([]); // prints "I am hungry"
alwaysHungry(["hello", 2, "Jay", "food", 34, 34, "food"]); // prints ["hello", 2, "Jay", "yummy", 34, 34, "yummy"]
alwaysHungry(["hello", 2, "Jay", "yummy", 34, 34]); // prints "I am hungry"

答案 3 :(得分:1)

这是您要找的东西。该代码可读性强,可以完成工作。

const yummy = ['hello', 2, 'Jay', 'food', 34, 34, 'food'],
      test1 = ['food'],
      test2 = ['hello', 2, 'Jay', 'foo', 34, 34, 'boo'],
      test3 = []

function acceptsArray(arr) {
  if (arr.length < 1 || !arr.includes('food')) console.log('I am hungry')
  else {
    arr.forEach((item, index, array) => {
      if (item === 'food') array[index] = 'yummy'
    })
    console.log(arr)
  }
}

acceptsArray(yummy) // ['hello', 2, 'Jay', 'yummy', 34, 34, 'yummy']
acceptsArray(test1) // ['yummy']
acceptsArray(test2) // I am hungry
acceptsArray(test3) // I am hungry

答案 4 :(得分:0)

您可以映射项目并替换它们,然后检查food是否在数组中。

const items = ["hello", 2, "Jay", "food", 34, 34, "food"]

let result = items.map(item => item == 'food' ? 'yummy' : item)

if (!result.includes('food') || result.length == 0) {
  console.log('I am hungry')
}

console.log(result)

答案 5 :(得分:0)

知道我迟到了,这是我的意见。

我使用了标准的for循环,没有使用ES6功能。

通常,例如在大学里,讲师希望您在接受.reduce()之类的方法之前,先了解它们的内部工作原理。 (那还是在我的大学里)。


我们可以使用计数器foodCounter来累积数组中"food"个字符串的数量。

  • 如果数组为空,代码将停止执​​行
  • 检查当前元素是否为string并忽略大小写。
  • 编辑其中包含"food"的值
  • 如果上述声明为foodCounter,则增加true
  • 最后检查foodCounter是否等于0

var arr  = [];
var arr1 = ["hello", 2, "Jay", "day", 34, 34, "day"];
var arr3 = ["hello", 2, "Jay", "fooD", 34, 34, "FOOd"];

function alwaysHungry(array) {
  let foodCounter = 0;
  
  // If array is not undefined
  if (!array) { console.log("I am hungry"); return; }
  // Iterate over the array
  for (let i = 0; i < array.length; i++) {
    // If element is a string and element is 'food' (case-insensitive)
    if (typeof array[i] === 'string' && array[i].toLowerCase() === 'food') {
      array[i] = 'yummy'; // Replace string to 'yummy'
      foodCounter++;      // Increment counter
    }
  }
  if (foodCounter === 0) { console.log("I am hungry"); }
}

console.log("No array");
alwaysHungry();

console.log("\nEmpty array");
alwaysHungry(arr);

console.log("\nNo 'food'");
alwaysHungry(arr1);

console.log("\nHas 'food'");
alwaysHungry(arr3);

答案 6 :(得分:-1)

通过试验所有示例,我可以得出以下结论:

function hungry(arr){
  var count = 0;
  for(var i =0; i<arr.length; i++){
    if(arr[i] == "food" || arr[i] == "Food"){
    count++;
    arr[i] = "yummy";
    }
  }
  if(count <=0){
    console.log("I am hungry");
  }
  else{
    console.log(arr);
  }
}
hungry(["hello", 2, "jay", "food", 34, 34, "food"]);
hungry([2,5,7,8,3,2, "string"]);
hungry([]);

输出为:

(7) ["hello", 2, "jay", "yummy", 34, 34, "yummy"]
I am hungry
I am hungry