如何在JavaScript中拆分0天15小时1分钟0秒并将其分配给不同的变量?

huangapple go评论83阅读模式
英文:

How To Split 0 Day 15 Hour 1 Min 0 Sec and assign it in different variable in java script?

问题

var time = "0 Day 15 Hour 1 Min 0 Sec";

// 从字符串中提取数字并赋值给变量
var day = parseInt(time.match(/\d+(?=\sDay)/)[0]);
var hour = parseInt(time.match(/\d+(?=\sHour)/)[0]);
var min = parseInt(time.match(/\d+(?=\sMin)/)[0]);
var sec = parseInt(time.match(/\d+(?=\sSec)/)[0]);

英文:

I have a string like this:

var time ="0 Day 15 Hour 1 Min 0 Sec";

How can I extract the numbers in the string into variables like below?

var day=0;
var hour=15;
var min=1;
var sec=0;

答案1

得分: 4

你可以使用全局正则表达式来匹配数字,然后立即解构以将这4个匹配项放入4个变量中:

var time = "0 Day 15 Hour 1 Min 0 Sec";
const [day, hour, min, sec] = time.match(/\d+/g);
console.log(day);
console.log(hour);
console.log(min);
console.log(sec);

请注意,以上是代码示例,用于提取时间中的数字并将其存储在相应的变量中。

英文:

You can use a global regular expression to match digits, then destructure immediately to put the 4 matches into 4 variables:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var time =&quot;0 Day 15 Hour 1 Min 0 Sec&quot;;
const [day, hour, min, sec] = time.match(/\d+/g);
console.log(day);
console.log(hour);
console.log(min);
console.log(sec);

<!-- end snippet -->

答案2

得分: 1

以下是代码段的翻译部分:

var time = "0 天 15 小时 1 分钟 0 秒";

var numericValue = [];
var textKey = [];
var result = {};
time.split(" ").map((value, index) => {
   return (
       (index + 1) % 2 == 0 ? 
       textKey.push(value.toLowerCase())
       : numericValue.push(Number(value))
   )
});

for (let i = 0; i < textKey.length; i++) {
  result[textKey[i]] = numericValue[i]
}
console.log(result);
console.log(result.day);

请注意,我已经将代码中的HTML实体编码(例如&lt;&gt;)还原为正常的JavaScript代码。

英文:

check out the code snippet:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

var time =&quot;0 Day 15 Hour 1 Min 0 Sec&quot;;

var numericValue=[];
var textKey=[];
var result={};
time.split(&quot; &quot;).map((value,index)=&gt; {
   return (
       (index+1)%2 == 0 ? 
       textKey.push(value.toLowerCase())
       : numericValue.push(Number(value))
   )
});

for(let i=0;i&lt;textKey.length;i++){
  result[textKey[i]]=numericValue[i]
}
console.log(result);
console.log(result.day);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年1月4日 12:24:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/59587866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定