Javascript 求三个单词的长度

Javascript 求三个单词的长度,javascript,Javascript,我有一个有三个单词的函数,我想返回这三个单词的最小长度。 我用Math.min()方法解决了这个问题,但我试着用reduce()方法解决了这个问题,但没有成功。 这是我的密码 const words = (w1, w2, w3) => { return Math.min(w1.length, w2.length, w3.length) } let output = words('hi', 'hello', 'good') console.log(outp

我有一个有三个单词的函数,我想返回这三个单词的最小长度。 我用
Math.min()
方法解决了这个问题,但我试着用
reduce()
方法解决了这个问题,但没有成功。 这是我的密码

    const words = (w1, w2, w3) => {
      return Math.min(w1.length, w2.length, w3.length)
    }

 let output = words('hi', 'hello', 'good') 
 console.log(output) // --> 2   
所以我要做的是让它与
reduce

一起工作 这就是我用
reduce

const words=(w1、w2、w3)=>{
设ar=[w1,w2,w3]
ar.reduce((a,i)=>i.length

非常感谢您提供的任何帮助。

您需要在reduce之后返回结果,并在reduce as内部返回

const words = (w1, w2, w3) => {
 let ar = [w1, w2, w3]
 return ar.reduce((a,i) => {
   debugger;
   if(i.length > a) {
     return i.length;
   }else{
     return ar[0].length;
   }
 }, ar[0].length)
}
const words=(w1、w2、w3)=>{
设ar=[w1,w2,w3]
返回ar.reduce((a,i)=>{
调试器;
如果(i.长度>a){
返回i.长度;
}否则{
返回ar[0]。长度;
}
},ar[0]。长度)
}
让输出=单词('hi'、'hello'、'good')

console.log(output)/-->2
您需要在reduce之后返回结果,并在reduce as内部返回

const words = (w1, w2, w3) => {
 let ar = [w1, w2, w3]
 return ar.reduce((a,i) => {
   debugger;
   if(i.length > a) {
     return i.length;
   }else{
     return ar[0].length;
   }
 }, ar[0].length)
}
const words=(w1、w2、w3)=>{
设ar=[w1,w2,w3]
返回ar.reduce((a,i)=>{
调试器;
如果(i.长度>a){
返回i.长度;
}否则{
返回ar[0]。长度;
}
},ar[0]。长度)
}
让输出=单词('hi'、'hello'、'good')

console.log(output)/-->2
检查中的reduce示例。累加器是第一次迭代的结果。记住这一点,更改减速机以返回两个字符串中较小的字符串

const words=(w1、w2、w3)=>{
设ar=[w1,w2,w3];
常数减速机=(a,i)=>a.lengthconsole.log(output)/-->2
检查中的reduce示例。累加器是第一次迭代的结果。记住这一点,更改减速机以返回两个字符串中较小的字符串

const words=(w1、w2、w3)=>{
设ar=[w1,w2,w3];
常数减速机=(a,i)=>a.lengthconsole.log(output)/-->2
使用reduce,您可以这样做:

const words=(w1、w2、w3)=>
[w1,w2,w3]。减少((最小,字)=>word.lengthconsole.log(单词“hi”、“there”、“how”)
使用reduce,您可以这样做:

const words=(w1、w2、w3)=>
[w1,w2,w3]。减少((最小,字)=>word.lengthconsole.log(words(“hi”,“there”,“how”)
您的解决方案完全有效您的解决方案完全有效您没有返回reduce的结果。您还需要使用第二个参数初始化
reduce
,可能是
无限
,并且只调用
i
上的
.length
(应该命名为
elem
,因为
i
意味着索引)。除此之外,
reduce
无论如何都是不合适的方法…
const shortest=(…args)=>Math.min(…args.map(e=>e.length))
words
不是一个很好的函数名。您没有返回reduce的结果。您还需要使用第二个参数初始化
reduce
,可能是
无限
,并且只调用
i
上的
.length
(应该命名为
elem
,因为
i
意味着索引)。除此之外,
reduce
无论如何都是一种不合适的方法…
const shortest=(…args)=>Math.min(…args.map(e=>e.length))
words
不是一个很好的函数名。谢谢@Russ Van Bert,我想把代码缩短一点;)谢谢@Russ Van Bert,我在想让代码变得简短;)嗨@Keith Nicholas,你的代码很棒,但我把它作为一个测试,所以我不能更改代码paramas@Th1更改为保持签名不变:)嗨@Keith Nicholas,你的代码太棒了,但我得到它是为了测试,所以我不能更改签名paramas@Th1更改为保持签名不变:)