gpt4 book ai didi

javascript - 函数内存在多个 'includes'

转载 作者:行者123 更新时间:2023-12-03 03:28:10 25 4
gpt4 key购买 nike

我正在寻找一种方法来访问对象内的“fit”和“gif”键。现在,我只能在页面上显示其中一个 - “fit”是图像,“gif”是 gif。

我想我可能可以使用 .match 但我不太确定正确的语法

谢谢

const sizeMappings = {
master: '1280',
small: '192w',
small_fit: '192w',
medium: '384w',
medium_low_res: '288w',
medium_fit: '384w',
medium_gif: '384w',
medium_fit_low_res: '288w',
large: '768w',
large_fit: '768w',
large_gif: '768w',
xlarge: '1280w',
xlarge_fit: '1280w',
}

const getSrcSet = (renditions, fit, gif) => {
const sizes = Object.keys(sizeMappings)
.map((key) => {
if (fit && !key.includes('fit')) return null
const mapping = `${renditions[key]} ${sizeMappings[key]}`
return mapping
})

return sizes
.filter(el => el !== null)
.join(',')
}

最佳答案

我会使用 filter() 而不是 map() 因为您实际上希望提取数组的子集。然后,只需将每个键匹配给定的尺寸名称 + "_gif" 或尺寸名称 + "_fit"

const sizeMappings = {
master: '1280',
small: '192w',
small_fit: '192w',
medium: '384w',
medium_low_res: '288w',
medium_fit: '384w',
medium_gif: '384w',
medium_fit_low_res: '288w',
large: '768w',
large_fit: '768w',
large_gif: '768w',
xlarge: '1280w',
xlarge_fit: '1280w',
}

let size = "large"; //change me

let arr = Object.keys(sizeMappings).filter(
(key) => (key === size + "_fit" || key === size + "_gif")
);

console.log(arr)

关于javascript - 函数内存在多个 'includes',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com