繁体   English   中英

将数组转换为逗号分隔的字符串

[英]Convert array to comma separated strings

classListadd方法只接受字符串而不接受数组( String [, String [, ...]] )所以我想知道是否有一种优雅的方法可以将数组转换为字符串列表而没有明显的循环:

var breakpoints = {
    "extraSmall"    : [ "only screen and (max-width: 575px)" ],
    "small"         : [ "only screen and (min-width: 576px) and (max-width: 767px)" ],
    "medium"        : [ "only screen and (min-width: 768px) and (max-width: 991px)" ],
    "large"         : [ "only screen and (min-width: 992px) and (max-width: 1199px)" ],
    "extraLarge"    : [ "only screen and (min-width: 1200px)" ],
}
Object.keys(breakpoints).map(feature => document.documentElement.classList.add(feature));

基本上,我希望在一次调用中添加多个类。

由于您不想创建新数组,因此请勿使用.map 相反,您想要执行副作用,因此您应该使用forEachfor循环:

for (const newClass of Object.keys(breakpoints)) {
  document.documentElement.classList.add(newClass)
}

为了避免完全循环,您可以(不雅地)与现有的className连接:

document.documentElement.className += ` ${Object.keys(breakpoints).join(' ')}`;

如果<html>标记还没有 class 名称,则不需要前导空格。 如果事先不确定它是否具有 class 名称,则改用classList.add会更容易。

由于add方法接受多个类作为参数,您可以在 object 键上使用扩展语法...将键中的每个元素作为 class 传递。

 var breakpoints = { "extraSmall": [ "only screen and (max-width: 575px)" ], "small": [ "only screen and (min-width: 576px) and (max-width: 767px)" ], "medium": [ "only screen and (min-width: 768px) and (max-width: 991px)" ], "large": [ "only screen and (min-width: 992px) and (max-width: 1199px)" ], "extraLarge": [ "only screen and (min-width: 1200px)" ],} const div = document.querySelector('div'); const classes = Object.keys(breakpoints); div.classList.add(...classes);
 <div>Div</div>

对于不支持扩展语法的旧版本浏览器,您可以使用apply方法。

 var breakpoints = { "extraSmall": [ "only screen and (max-width: 575px)" ], "small": [ "only screen and (min-width: 576px) and (max-width: 767px)" ], "medium": [ "only screen and (min-width: 768px) and (max-width: 991px)" ], "large": [ "only screen and (min-width: 992px) and (max-width: 1199px)" ], "extraLarge": [ "only screen and (min-width: 1200px)" ],} const div = document.querySelector('div'); const classes = Object.keys(breakpoints); div.classList.add.apply(div.classList, classes)
 <div>Div</div>

暂无
暂无

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

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