簡體   English   中英

剝離 Javascript 中的部分數組值

[英]Stripping out part of array value in Javascript

我有一個數組,我目前正在使用 map function 分解它,以便僅獲取原始數組的選項索引。 這行得通,但現在我想把它去掉,只從該選項索引中獲取前 2 個數字(或者更具體地說,該值中“-”前面的任何內容)

在按照我目前的方式映射它時,只去掉這些數字的最佳方法是什么?

 var vm = new Vue({ el: "#app", data: { options: [ {id:100, option:"1 - John Doe"}, {id:200, option:"2 - Jane Doe"} ] }, methods: { getNames(){ let names = this.options.map(option => { return { id: option.option } }); console.log(names); } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @click="getNames()">TEST</button> </div>

您可以編輯map回調以獲取字符串的第一部分:

 let options = [ {id:100, option:"1 - John Doe"}, {id:200, option:"2 - Jane Doe"} ]; let names = options.map(option => { let opt = option.option; id = opt.split(' - ')[0]; return { id }; }); console.log(names);

const names = this.options.map(option => {
    const text = option.option // Get raw text from 'option'
    const parts = text.split('-') // Split text string by the '-' (returns an array, E.g. ["1 ", " John Doe"])
    return parts[0] // The first element of 'parts' is the result you are looking for (note it is a string, not a number)
})

純 JavaScript 只返回字符串中的數字

返回數組的示例:

[
  {id: "1"},
  {id: "2"}
]

解決方案

使用正則表達式replace從字符串中刪除任何非數字 - 僅返回數字(作為字符串)。

正則表達式適用於所有使用斜線后面的全局標志的事件//g 斜線內的模式可以是任何等價物,以僅保留數字:

  • \D匹配所有非數字字符(元字符)
  • [^0-9]匹配所有非數字字符(反轉字符范圍)

演示:

 let options = [ {id:100, option:"1 - John Doe"}, {id:200, option:"2 - Jane Doe"} ]; // keep only the first digits before hyphen let names = options.map(o => { return {id: o.option.replace(/[^0-9]/g, "")}; }); console.log(names);

您可以使用字符串的split方法將字符串通過" - "拆分並獲得第一部分(數字)。 此外,您可以使用parseInt function 將字符串轉換為整數。

 var vm = new Vue({ el: "#app", data: { options: [ {id:100, option:"1 - John Doe"}, {id:200, option:"2 - Jane Doe"} ] }, methods: { getNames(){ let names = this.options.map(option => { return { id: parseInt(option.option.split(" - ")) } }); console.log(names); } } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <button @click="getNames()">TEST</button> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM