[英]Javascript function calling inside an array of objects?
I googled a lot but no find a satisfying answer.我用谷歌搜索了很多,但没有找到满意的答案。 Searching for a typing error in typescript faced the such code:
在打字稿中搜索打字错误面临这样的代码:
// @strict: false
let suits = ["hearts", "spades", "clubs", "diamonds"];
function pickCard(x: any): any {
// Check to see if we're working with an object/array
// if so, they gave us the deck and we'll pick the card
if (typeof x == "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
}
// Otherwise just let them pick the card
else if (typeof x == "number") {
let pickedSuit = Math.floor(x / 13);
return { suit: suits[pickedSuit], card: x % 13 };
}
}
let myDeck = [
{ suit: "diamonds", card: 2 },
{ suit: "spades", card: 10 },
{ suit: "hearts", card: 4 },
];
let pickedCard1 = myDeck[pickCard(myDeck)]; //<--- HERE IS DOUBT
alert("card: " + pickedCard1.card + " of " + pickedCard1.suit);
let pickedCard2 = pickCard(15);
alert("card: " + pickedCard2.card + " of " + pickedCard2.suit);
I like to understand what such an expression is that?我想明白这样的表达是什么? Am i calling a function inside an array of objects passing that array as a parameter?
我是否在传递该数组作为参数的对象数组中调用函数? That's correct?
那是正确的吗? And Why a cant call the function straight like this:
为什么不能像这样直接调用函数:
let pickedCard1 = pickCard(myDeck);
Always I do i got undefined as return.我总是做我未定义作为回报。 Sorry the jr question but i am trying to understand javascript better.Thanks guys
抱歉 jr 的问题,但我想更好地理解 javascript。谢谢大家
You're problem is that you've left something off of your object
branch - you're returning number
instead of a Card
:你的问题是你在你的
object
分支上留下了一些东西 - 你返回的是number
而不是Card
:
let pickedCard: number = Math.floor(Math.random() * x.length);
// This is really `pickedCardIndex`
Instead, check that the passed in value is an Array using Array.isArray
and then index out of the array as your last step:相反,检查传入的值是否是使用
Array.isArray
的数组,然后作为最后一步从数组中索引:
if (Array.isArray(x)) {
let pickedCardIndex = Math.floor(Math.random() * x.length);
return x[pickedCardIndex];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.