简体   繁体   English

JavaScript 点阵分割

[英]JavaScript Split Array on Dot

I have a Javascript Array that contains the file name and its extension such as this:我有一个包含文件名及其扩展名的 Javascript 数组,例如:

let files = ["Apple.docx", "Cat.jpeg", "Moon.gif"];

I want to make it so the extensions like (.docx, .jpeg and.gif) are stored in another array and also uppercase as this while the original array just becomes:我想这样做,以便将(.docx、.jpeg 和 .gif)之类的扩展名存储在另一个数组中,并且在原始数组变成:

let files = ["Apple", "Cat", "Moon"];
let extensions = ['DOCX', 'JPEG', 'GIF'];

You can just use String.split() method.您可以只使用String.split()方法。 About extension, you can use String.toUpperCase() .关于扩展,您可以使用String.toUpperCase()

 const files = ["Apple.docx", "Cat.jpeg", "Moon.gif"]; const names = [], extensions = []; files.forEach(name => { const splitted = name.split("."); names.push(splitted[0]); extensions.push(splitted[1].toUpperCase()); }); console.log(names, extensions);

 const extensions = []; const files = ["Apple.docx", "Cat.jpeg", "Moon.gif"].map(x => { const idx = x.lastIndexOf("."); if (idx === -1) { extensions.push(""); return x; } extensions.push(x.substring(idx + 1).toUpperCase()); return x.substring(0, idx); }); console.log(files); console.log(extensions);

 let files = ["Apple.docx", "Cat.jpeg", "Moon.gif"]; extensions = files.map(e => (e.split('.')[1]).toUpperCase()) console.log(extensions)

Try:尝试:

let files = ["Apple.docx", "Cat.jpeg", "Moon.gif"];
let extensions = [];
let newFiles = [];
files.map((val)=>{
    newFiles.push(val.split('.')[0]); // files name without extension
    extensions.push(val.split('.')[1]); // extensions of files.
});

Below is one of the ways using String.split , Array.reduce & Destructuring assignment in order to achieve the expected output.以下是使用String.splitArray.reduceDestructuring assignment的方法之一,以实现预期的 output。

 let files = ["Apple.docx", "Cat.jpeg", "Moon.gif"]; const formatFiles = files => { return files.reduce((res, file) => { //split and assign the values using destructuring assignment const [name, ext] = file.split("."); res.names.push(name); res.exts.push(ext.toUpperCase()); return res; }, {names: [], exts:[]}); } console.log(formatFiles(files));
 .as-console-wrapper{ max-height: 100%;important; }

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

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