繁体   English   中英

有人能告诉我这里出了什么问题吗? 我想用大写字母返回蔬菜数组

[英]Can someone tell me what is wrong here? I want to return the vegetable array in CAPITAL letters

 let vegetables = ["cucumbers", "carrots", "tomatoes"]; let upperCase = function() { for (let i = 0; i <= vegetables.length; i++) { vegetables[i].toUpperCase(); } return vegetables[i]; }; console.log(upperCase());

我认为 toUpperCase() 方法返回一个字符串值,而不是改变你的值,所以你需要像这样做vegetables[i] = vegetables[i].toUpperCase();

let vegetables = ["cucumbers", "carrots", "tomatoes"];

let upperCase = function(){
    return vegetables.map( vegetable => vegetable.toUpperCase())
}

console.log(upperCase()); // [ 'CUCUMBERS', 'CARROTS', 'TOMATOES' ]

// 或者你也可以这样做

let vegetables = ["cucumbers", "carrots", "tomatoes"];

let upperCase = () => vegetables.map( vegetable => vegetable.toUpperCase())

console.log(upperCase());
  1. vegetables[i].toUpperCase()不会替换数组值,upperCase 不能“就地”工作
  2. 如果选择console.log(upperCase())则需要返回结果
    而不是做upperCase(); console.log(vegetables) upperCase(); console.log(vegetables)
  3. 您使用<=超出了数组 - 它应该是<因为 arrays 是基于零的。

这是您的固定版本

 let vegetables = ["cucumbers", "carrots", "tomatoes"]; let upperCase = function() { for (let i = 0; i < vegetables.length; i++) { vegetables[i] = vegetables[i].toUpperCase(); } return vegetables; }; console.log(upperCase());

这是 2022 年的版本

 const upperCase = arr => arr.map(item => item && typeof item === 'string'? item.toUpperCase(): item) let vegetables = ["cucumbers", "carrots", "tomatoes"]; console.log(upperCase(vegetables));

分解

const upperCase // name of method  
= arr // passing something we call arr  
=>    // arrow function - note we do not need "{ return ... }" if there is only one processing statement  
arr.map(   // return a map (array) of the passed array, e.g. do not modify the passed array   
item => // each element is processed as item  
item && typeof item === 'string' // if item is not falsy and is a string  
? item.toUpperCase() // return item uppercased  
: item) // else return the item (this construct is called a ternary)  
let vegetables = ["cucumbers", "carrots", "tomatoes"];

let upperCase = function() {
    let lst=[]
  for (let i = 0; i < vegetables.length; i++) {
    lst.push(vegetables[i].toUpperCase());
  }
  return lst
  
};

console.log(upperCase());

运行此代码:)

在 for 循环中应该迭代直到 i< vegetables.length。 如果不是我们尝试转换大写,未定义的东西。 然后我们得到错误

使用 ES6 数组方法

 let vegetables = ["cucumbers", "carrots", "tomatoes"]; let upperCase = vegetables.map(el => el.toUpperCase()); console.log(upperCase);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM