在Javascript中获取数组中每个字符串的第一个字符

时间:2017-10-31 12:43:36

标签: javascript arrays loops

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

let secretMessage = animals.map(function(animal) {
     for(animal = 0; animal <= animals.length-1; animal++) {
            return animals[animal].charAt(animal);
     }
});

console.log(secretMessage.join(''));

嗨,通过这段代码我想输出字符串HelloWorld,它由animals数组中每个字符串/元素的第一个字符组成。但是,输出是HHHHHHHHHH。我不知道for循环是否存在问题?

有人可以告诉我为什么代码产生这样的输出以及我如何修改它以便成功返回所需的结果?

我现在只是一个新手&amp;这就是为什么你的帮助将在我作为程序员的成长中发挥巨大作用的原因。提前谢谢!

9 个答案:

答案 0 :(得分:4)

Map本身就是for loop

尝试:

// Animals.
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog']
    
// Secret Message.
const secretMessage = animals.map((animal) => animal[0]).join('')
    
// Log.
console.log(secretMessage) // "HelloWorld"

或者:

// Animals.
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog']

// Secret Message.
const secretMessage = animals.reduce((accumulator, animal) => accumulator + animal[0], '')

// Log.
console.log(secretMessage) // "HelloWorld"

答案 1 :(得分:3)

map方法为你做for循环。所以你在函数中所需要的只是animal [0]

using Abp;
using Abp.Zero.Ldap.Authentication;
using Abp.Zero.Ldap.Configuration;
using MCMT.Quotes.Authorization.Users;
using MCMT.Quotes.MultiTenancy;
using System.Threading.Tasks;
using System.DirectoryServices.AccountManagement;

namespace MCMT.Quotes.Authorization.Ldap
{
    public class AppLdapAuthenticationSource : LdapAuthenticationSource<Tenant, User>
    {
        private readonly ILdapSettings _settings;
        private readonly IAbpZeroLdapModuleConfig _ldapModuleConfig;

        public AppLdapAuthenticationSource(ILdapSettings settings, IAbpZeroLdapModuleConfig ldapModuleConfig)
            : base(settings, ldapModuleConfig)
        {
            _settings = settings;
            _ldapModuleConfig = ldapModuleConfig;
        }

        public async override Task<User> CreateUserAsync(string userNameOrEmailAddress, Tenant tenant)
        {
            await CheckIsEnabled(tenant);

            var user = await base.CreateUserAsync(userNameOrEmailAddress, tenant);

            using (var principalContext = await CreatePrincipalContext(tenant))
            {
                var userPrincipal = UserPrincipal.FindByIdentity(principalContext, userNameOrEmailAddress);

                if (userPrincipal == null)
                {
                    throw new AbpException("Unknown LDAP user: " + userNameOrEmailAddress);
                }

                UpdateUserFromPrincipal(user, userPrincipal);

                user.IsEmailConfirmed = true;
                user.IsActive = false;

                return user;
            }
        }

        public async override Task UpdateUserAsync(User user, Tenant tenant)
        {
            await CheckIsEnabled(tenant);

            await base.UpdateUserAsync(user, tenant);

            using (var principalContext = await CreatePrincipalContext(tenant))
            {
                var userPrincipal = UserPrincipal.FindByIdentity(principalContext, user.UserName);

                if (userPrincipal == null)
                {
                    throw new AbpException("Unknown LDAP user: " + user.UserName);
                }

                UpdateUserFromPrincipal(user, userPrincipal);
            }
        }

        protected override void UpdateUserFromPrincipal(User user, UserPrincipal userPrincipal)
        {
            user.UserName = userPrincipal.SamAccountName;
            user.Name = userPrincipal.GivenName;
            user.Surname = userPrincipal.Surname;
            user.EmailAddress = userPrincipal.EmailAddress;
        }

        private async Task CheckIsEnabled(Tenant tenant)
        {
            if (!_ldapModuleConfig.IsEnabled)
            {
                throw new AbpException("Ldap Authentication module is disabled globally!");
            }

            var tenantId = GetIdOrNull(tenant);
            if (!await _settings.GetIsEnabled(tenantId))
            {
                throw new AbpException("Ldap Authentication is disabled for given tenant (id:" + tenantId + ")! You can enable it by setting '" + LdapSettingNames.IsEnabled + "' to true");
            }
        }

        private static int? GetIdOrNull(Tenant tenant)
        {
            return tenant == null
                ? (int?)null
                : tenant.Id;
        }
    }
}

这将返回数组中每个字符串中的每个第一个字符,即动物。你拥有的其他一切都是对的。

答案 2 :(得分:1)

你不需要内循环:

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

let secretMessage = animals.map(function(animal) {
  return animal.charAt(0); // or simply animal[0]
});

console.log(secretMessage.join(''));

答案 3 :(得分:0)

这里的错误是你在map函数中有一个循环,它已经循环了数组。

正确的代码是

animals.map(x=>x[0]).join('');
//or
animals.map(function(animal){
    return animal[0]; //First letter of word
}).join(''); //Array -> String

答案 4 :(得分:0)

这应该是代码:

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

let secretMessage = animals.map(function(animal) {
    return animal.charAt(0);
});

console.log(secretMessage.join(''));

答案 5 :(得分:0)

就这样做。

&#13;
&#13;
let animals = [
  'Hen', 'elephant', 'llama', 
  'leopard', 'ostrich', 'Whale', 
  'octopus', 'rabbit', 'lion', 'dog'
];
console.log(animals.map(e => e[0]).join(""));
&#13;
&#13;
&#13;

答案 6 :(得分:0)

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

let secretMessage = animals.map(function(animals) {
return animals[0];
});

console.log(secretMessage.join(''));

let animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

let secretMessage = animals.map(animals => animals[0]);

console.log(secretMessage.join(''));

答案 7 :(得分:0)

.map() array函数将回调函数作为参数并返回新数组,以便可以使用此方法获取结果,请参见以下语法:

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];


 const secretMessage = animals.map(animals => {

   return animals[0];
 })

console.log(secretMessage.join(''));

现在将.map方法应用于动物数组时,它仅返回每个字符串的第一个元素,因为我们使用animals[0],它仅读取每个字符串的第一个元素,因此我们的输出为HelloWorld < / p>

答案 8 :(得分:0)

const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];

const secretMessage = animals.map(animal => {
  return animal[0];
})

console.log(secretMessage.join(''));